Skip to content


ardupilot  None  ros2  dds  micro ros  xrce  sitl  plugin  SITL  debug  rangefinder  pymavlink  mavros  gazebo  distance sensor  system_time  timesync  cmake  gtest  ctest  101  cpp  c++  format  fmt  multithreading  spdlog  cyclonedds  eprosima  fastdds  simulation  config  ignition  bridge  sdf  tips  ign-transport  camera  sensors  lidar  aptly  apt  repository  mirror  encryption  pgp  docker  nvidia  git  bundle  submodules  github  hooks  pre-commit  lxd  container  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  mkdocs  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  gi  kml  python  geo  snippets  cheat Sheet  asyncio  future  click  cli  numpy  project  template  black  isort  templates  cookiecutter  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  from a-z  mock  iterator  generator  logging  tuple  namedtuple  typing  annotation  typever  pyzmq  zmq  msgpack  action  namespace  remap  control2  ros2_control  gdb  qos  tag  plugins  msg  node  zero-copy  shm  tutorial  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  rpi  arm  qemu  settings  behavior  py_trees  bt  behavior_trees  blackboard  plot  visualization  debugging  diagnostic  DiagnosticTask  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  model  cook  gps  imu  ray  gazebo_ros_ray_sensor  ultrsonic  range  ultrasonic  gazebo classic  wrench  effort  odom  ign  gz  xacro  ros_ign  diff_drive  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  slam  test  rclpy  goal abort  cancel goal  action client  action server  custom messages  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  deb  package  setup  local_setup  rosdep  package manager  project settings  vcstool  urdf  robot_state_publisher  urdf_to_graphiz  joint  link  cross-compiler  nano  texture  tmuxp  loop device  rootfs  embedded  zah  linux  rm  ubuntu  sudo  sudoers  nopasswd  visudo  udev  ip  ss  network  netstat  snap  deploy  ssh  systemd  socat  networking  serial  udp  tc  mtu  select  robotics  kalman_filter  kalman  filter  control  extensions  json  yaml  schema  yocto  poky  projects  courses to follow  world  gazebo_ros2_control  position_controller  effort_controller  velocity_controller  gazebo_ros_force  gazebo_ros_joint_state_publisher  joint_state_publisher  vrx  buoyancy 

Part3 - Simple python Node with parameter

Basic ROS2 node with parameter, declare, read with type, set from command line or using yaml file, get and set from command line or gui


Objective#

  • Declare parameter
  • Manage params from cli
  • Set node params with launch file

Code example#

import rclpy
from rclpy.node import Node

class TestParams(Node):

    def __init__(self):
        super().__init__('test_params_rclpy')

        self.declare_parameter('my_str')
        self.declare_parameter('my_int', value=10)
        self.declare_parameter('my_double_array')

        timer_period = 2
        self.timer = self.create_timer(timer_period, self.timer_callback)

    def timer_callback(self):
        my_param = self.get_parameter('my_str').get_parameter_value().string_value
        my_param_int = self.get_parameter("my_int").get_parameter_value().integer_value
        self.get_logger().info(f"Hello {my_param}! with int data: {my_param_int}")

def main(args=None):
    rclpy.init(args=args)
    node = TestParams()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

if __name__ == "__main__":
    main()

Manage params from cli#

Run node with param#

Note

Run node with arguments from CLI --ros-args -p <param_name>:=<param_value>

ros2 run basic simple_param --ros-args -p my_str:=world
# Result
[INFO] [1649226981.611616597] [test_params_rclpy]: Hello world! with int data: 10
[INFO] [1649226983.604038327] [test_params_rclpy]: Hello world! with int data: 10

Manage params from cli#

# list params from all running nodes
ros2 param list
# Result 
/simple_params:
  my_double_array
  my_int
  my_str
  use_sim_time

YAML file#

simple.yaml
simple_params:
  ros__parameters:
    my_str: "world from yaml"
    my_int: 100
    my_double_array: [1.0, 2.0, 3.0]

Warning

ros__parameters with double underline

Run with yaml#

terminal1
ros2 run basic simple_param --ros-args --params-file /home/user/dev_ws/src/basic/config/simple.yaml
[INFO] [1649227913.033306747] [simple_params]: Hello world from yaml! with int data: 100
[INFO] [1649227915.025466940] [simple_params]: Hello world from yaml! with int data: 100

Params yaml and launch file#

  • place yaml file in config syb folder
  • copy config folder to output folder using setup.py

yaml copy
data_files=[
        ('share/ament_index/resource_index/packages', ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
        (os.path.join("share", package_name), glob("launch/*.launch.py")),
        (os.path.join("share", package_name, "config"), glob("config/*")),
    ],
simple_param_yaml.launch.py
# with yaml file
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
    ld = LaunchDescription()
    config = os.path.join(
        get_package_share_directory('basic'),
        'config',
        'simple.yaml'
        )

    node=Node(
        name="simple_params",
        package = 'basic',
        executable = 'simple_param',
        parameters = [config]
    )
    ld.add_action(node)
    return ld

Warning

The name argument in the launch Node object must be the same in the param yaml file

simple_param.launch.py
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
    ld = LaunchDescription()

    node=Node(
        name="simple_params",
        package = 'basic',
        executable = 'simple_param',
        parameters = [
            {"my_str": "hello from launch"},
            {"my_int": 1000},
            {"my_double_array": [1.0, 10.0]}
        ]
    )
    ld.add_action(node)
    return ld

References#